<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

class AccessLog
{
    /**
     * 路由全局中间件
     *
     * @param Request $request
     * @param Closure $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next): mixed
    {
        // 请求开始时间
        $requestTime = microtime(true);

        // 请求唯一标识
        $trace_id = (string)Str::uuid();
        Log::withContext(["request-id" => $trace_id]);

        // 发送邮件标识
        Log::withContext(['send-mail' => true]);

        $response = $next($request);

        // 请求结束时间
        $rq_time = microtime(true) - $requestTime;
        $log = [
            'method'      => $request->method(),
            'url'         => $request->fullUrl(),
            'param'       => $request->all(),
            'response'    => $response->getContent(),
            'req_header'  => $request->header(),
            'resp_header' => $response->headers->all(),
            'ip_address'  => $request->ip(),
            'rq_time'     => sprintf("%.2f", $rq_time),
        ];

        Log::info("[access_log]", $log);
        return $response;
    }
}
